package com.headfirst.dmp.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 高德地图API服务
 * <p>
 * 通过经纬度，查询到对应的商圈信息
 */
public class GaodeGeoAPI {

    /**
     * 通过经纬度信息，查询到对应的商圈信息
     *
     * @param latAndLongs
     * @return
     * @throws Exception
     */
    public static String getBuuiness(String latAndLongs) throws Exception {

        String key = "115aaa29fded3540f0715caa1071663a";
        String location = latAndLongs;
        String extensions = "all";    //查询基本信息

        //通过HttpClient请求百度GeoAPI，获取Bussiness商圈信息
        CloseableHttpClient aDefault = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("https://restapi.amap.com/v3/geocode/regeo?key=" + key + "&location=" + location + "&extensions=" + extensions);
        CloseableHttpResponse response = aDefault.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String info = EntityUtils.toString(entity);   //查询到的结果

        //将数据解析成Json格式
        JSONObject jsonObject = JSONObject.parseObject(info);

        String businessName = null;


        JSONArray arrayjson = jsonObject.getJSONObject("regeocode")
                                .getJSONObject("addressComponent")
                                .getJSONArray("businessAreas");

        if(null != arrayjson && arrayjson.size()>0 ){
            if(!(arrayjson.get(0) instanceof JSONArray)){
                businessName = arrayjson.getJSONObject(0).getString("name");
            }
        }else{
            JSONArray jsonArray = jsonObject.getJSONObject("regeocode") .getJSONArray("pois");
            if (null != jsonArray && jsonArray.size() > 0) {
                businessName = jsonArray.getJSONObject(0).getString("name");
            }

        }

        return businessName;
    }

}
